/**
 * User实体类
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.entity;

import com.sxf.crm.core.entity.Role;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

@Data
@Entity
@Table(name = "users")
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id; // 用户ID，主键

    @Column(nullable = false, unique = true)
    private String username; // 用户名(登录账号)

    @Column(nullable = false)
    private String password; // 密码(加密存储)

    @Column(nullable = false)
    private String realName; // 真实姓名

    @Column(name = "phone_number")
    private String phoneNumber; // 手机号码

    @Column(name = "email")
    private String email; // 电子邮箱

    @Column(name = "avatar_url")
    private String avatarUrl; // 头像URL

    @Column(name = "department_id")
    private Long departmentId; // 所属部门ID

    @Column(name = "position")
    private String position; // 职位

    @Column(name = "status")
    private Integer status; // 用户状态(0-禁用, 1-启用, 2-锁定)

    @Column(name = "last_login_time")
    private Long lastLoginTime; // 最后登录时间

    @Column(name = "create_at")
    private Long createAt;

    @Column(name = "create_user_id")
    private Long createUserId;

    @Column(name = "update_at")
    private Long updateAt;

    private Long updateUserId;

    @Column(nullable = false)
    private boolean isAdmin; // 是否管理员

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
        name = "user_roles",
        joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    private Set<Role> roles; // 用户角色集合(多对多关系，通过中间表user_roles关联)
    
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles.stream()
                .flatMap(role -> role.getPermissions().stream())
                .map(permission -> new SimpleGrantedAuthority(permission.getName()))
                .collect(Collectors.toSet());
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
